package com.lfg.leetcode.leetcode0;


import com.alibaba.fastjson.JSONArray;

import java.util.ArrayList;
import java.util.List;

public class No57insert {

    public static void main(String[] args) {
        int[][] list = new int[][]{{1, 3}, {6, 8}};
        int[][] ret = insert(list, new int[]{0, 9});
        System.out.println(JSONArray.toJSONString(ret));
    }

    public static int[][] insert(int[][] intervals, int[] newInterval) {
        int left = newInterval[0];
        int right = newInterval[1];
        boolean canAdd = true;
        int i = 0;
        List<int[]> list = new ArrayList<>(intervals.length);
        for (; i < intervals.length; i++) {
            int[] data = intervals[i];
            if (data[0] > right) {
                if (canAdd) {
                    list.add(new int[]{left, right});
                    canAdd = false;
                }
                list.add(data);
            } else if (data[1] < left) {
                list.add(data);
            } else {
                left = Math.min(left, data[0]);
                right = Math.max(right, data[1]);
            }
        }
        if (canAdd) {
            list.add(new int[]{left, right});
        }
        int index = 0;
        int[][] ret = new int[list.size()][2];
        for (int[] d : list) {
            ret[index++] = d;
        }
        return ret;
    }


}

